package sdk.webview.fmc.com.fmcsdk.activity;

import static android.os.Environment.DIRECTORY_PICTURES;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileUtils;
import android.os.StrictMode;
import android.os.storage.StorageManager;
import android.preference.PreferenceManager;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.heytap.mcssdk.utils.Utils;
import com.tencent.smtt.sdk.MimeTypeMap;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import id.zelory.compressor.Compressor;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.barcode.common.Config;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.bean.H5UploadImage;
import sdk.webview.fmc.com.fmcsdk.bean.SystemSetting;
import sdk.webview.fmc.com.fmcsdk.bean.UploadImage;
import sdk.webview.fmc.com.fmcsdk.bean.User;
import sdk.webview.fmc.com.fmcsdk.check.CacheHelper;
import sdk.webview.fmc.com.fmcsdk.db.DBManager;
import sdk.webview.fmc.com.fmcsdk.db.IMAGE;
import sdk.webview.fmc.com.fmcsdk.db.Record;
import sdk.webview.fmc.com.fmcsdk.interfaces.PresionInfoView;
import sdk.webview.fmc.com.fmcsdk.presenter.PresionInfoPresenter;
import sdk.webview.fmc.com.fmcsdk.util.AESUtil;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.HandleJsEvent;
import sdk.webview.fmc.com.fmcsdk.util.ImageCompressor;
import sdk.webview.fmc.com.fmcsdk.util.ImageSelector;
import sdk.webview.fmc.com.fmcsdk.util.ImageUtils;
import sdk.webview.fmc.com.fmcsdk.util.PreferencesHelper;
import sdk.webview.fmc.com.fmcsdk.util.SdkVersionUtils;
import sdk.webview.fmc.com.fmcsdk.util.SharedPrefUtils;
import sdk.webview.fmc.com.fmcsdk.util.SnackBarUtil;
import sdk.webview.fmc.com.fmcsdk.util.TitleBar;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ApiFactory;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.RxBus;
import sdk.webview.fmc.com.fmcsdk.view.AvatarSelectDialog;
import sdk.webview.fmc.com.fmcsdk.view.ChangePasswordDialog;
import sdk.webview.fmc.com.fmcsdk.view.CircleImageView;
import sdk.webview.fmc.com.fmcsdk.view.EditPwdDialog;
import sdk.webview.fmc.com.fmcsdk.view.EditTextDialog;
import sdk.webview.fmc.com.fmcsdk.view.MarqueeTextView;
import sdk.webview.fmc.com.fmcsdk.view.UploadIamgeDialog;
import top.zibin.luban.OnCompressListener;

//import com.jph.takephoto.app.TakePhoto;
//import com.jph.takephoto.app.TakePhotoImpl;
//import com.jph.takephoto.compress.CompressConfig;
//import com.jph.takephoto.model.CropOptions;
//import com.jph.takephoto.model.InvokeParam;
//import com.jph.takephoto.model.TContextWrap;
//import com.jph.takephoto.model.TException;
//import com.jph.takephoto.model.TResult;
//import com.jph.takephoto.permission.InvokeListener;
//import com.jph.takephoto.permission.PermissionManager;
//import com.jph.takephoto.permission.TakePhotoInvocationHandler;

/**
 * 个人信息
 */
public class PresionInfoActivity extends BaseActivity<PresionInfoView, PresionInfoPresenter> implements PresionInfoView, View.OnClickListener {

    TitleBar titlebar;
    TextView tvPhone;
    RelativeLayout rlPhone;
    TextView tvEmail;
    RelativeLayout rlEmail;
    RelativeLayout rlModifyPassword;
    CircleImageView myAvatar;
    TextView tvFullname;
    TextView tvAccount;
    TextView tvPost;
    MarqueeTextView tvDepartment;
    TextView tvPhoneFlag;
    ImageView ivPhoneArrow;
    TextView tvEmailFlag;
    TextView tvLogout, tv_zhuxiao;
    RelativeLayout testUrl;
    RelativeLayout rlDepartmentFlag;
    User user;

    private List<Record> recordList;//数据库里未上传的图片集合
    //    private UploadIamgeDialog iamgeDialog;//上传图片的dialog
    private Uri uritempFile;

    private Snackbar snackbar;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_presion_info;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        findView();
//        testUrl.setVisibility(View.VISIBLE);
        titlebar.setTitle(getString(R.string.presion_setting));
        titlebar.setRightImage(R.mipmap.setting);
        titlebar.setRightImgOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getViewContext(), SettingActivity.class));
            }
        });
        //回显本地保存的用户信息
        user = PreferencesHelper.getData(User.class);
        if (user == null) {
            return;
        }

        setUserInfo(user.getRecord());
        SystemSetting systemSetting = PreferencesHelper.getData(SystemSetting.class);
        String mobile_font_color = systemSetting.getRecord().getMOBILE_FONT_COLOR();
        if (!TextUtils.isEmpty(mobile_font_color)) {
//            tvLogout.setTextColor(Color.parseColor(mobile_font_color));
        }
    }

    private void findView() {
        titlebar = (TitleBar) findViewById(R.id.titlebar);
        tvPhone = (TextView) findViewById(R.id.tv_phone);
        rlPhone = (RelativeLayout) findViewById(R.id.rl_phone);
        tvEmail = (TextView) findViewById(R.id.tv_email);
        rlEmail = (RelativeLayout) findViewById(R.id.rl_email);
        rlModifyPassword = (RelativeLayout) findViewById(R.id.rl_modify_password);
        myAvatar = (CircleImageView) findViewById(R.id.my_avatar);
        tvFullname = (TextView) findViewById(R.id.tv_fullname);
        tvAccount = (TextView) findViewById(R.id.tv_account);
        tvPost = (TextView) findViewById(R.id.tv_post);
        tvDepartment = (MarqueeTextView) findViewById(R.id.tv_department);
        tvPhoneFlag = (TextView) findViewById(R.id.tv_phone_flag);
        ivPhoneArrow = (ImageView) findViewById(R.id.iv_phone_arrow);
        tvEmailFlag = (TextView) findViewById(R.id.tv_email_flag);
        tvLogout = (TextView) findViewById(R.id.tv_logout);
        tv_zhuxiao = (TextView) findViewById(R.id.tv_zhuxiao);
        testUrl = (RelativeLayout) findViewById(R.id.test_url);
        rlDepartmentFlag = (RelativeLayout) findViewById(R.id.rl_department_flag);
        RelativeLayout rl_post_flag = (RelativeLayout) findViewById(R.id.rl_post_flag);
        RelativeLayout rl_name = (RelativeLayout) findViewById(R.id.rl_name);
        RelativeLayout rl_icon = (RelativeLayout) findViewById(R.id.rl_icon);
        rlPhone.setOnClickListener(this);
        rlEmail.setOnClickListener(this);
        rlModifyPassword.setOnClickListener(this);
        tvPhone.setOnClickListener(this);
        testUrl.setOnClickListener(this);
        tvLogout.setOnClickListener(this);
        tv_zhuxiao.setOnClickListener(this);
        rlDepartmentFlag.setOnClickListener(this);
        rl_post_flag.setOnClickListener(this);
        rl_name.setOnClickListener(this);
        rl_icon.setOnClickListener(this);
        String isShowAvatar = sharedPrefs.getString(Constant.ISSHOWAVATAR, "0");
        if (isShowAvatar.equals("0")) {
            rl_icon.setVisibility(View.GONE);
        } else {
            rl_icon.setVisibility(View.VISIBLE);
        }
        boolean isSdk = sharedPrefs.getBoolean(Constant.IS_SDK, false);
        if (isSdk) {
            tvLogout.setVisibility(View.INVISIBLE);
        }


//        tv_zhuxiao.setVisibility(View.GONE);  //上架市场需要 注销  其他时候隐藏掉
    }


    @Override
    protected PresionInfoPresenter createPresenter() {
        return new PresionInfoPresenter();
    }


    int i = 0;
    int y = 0;
    int x = 0;

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rl_department_flag) {
            ++i;
            if (y == 1 && i > 15 && x > 15) {
                testUrl.setVisibility(View.VISIBLE);
            }
        } else if (id == R.id.rl_post_flag) {
            ++y;
        } else if (id == R.id.rl_name) {
            ++x;
        } else if (id == R.id.tv_phone) {
            final EditTextDialog editTextDialog = new EditTextDialog(this, getString(R.string.phone), getString(R.string.hint_setting_phone));
            editTextDialog.show();
            editTextDialog.setClicklistener(new EditTextDialog.ClickListenerInterface() {
                @Override
                public void doConfirm(String content) {
                    if (TextUtils.isEmpty(content)) {
                        ToastMessage(context.getString(R.string.wrongful_phone));
                        return;
                    }
                    if (content.length() <= 4) {
                        ToastMessage(context.getString(R.string.wrongful_phone));
                        return;
                    }

                    /**修改手机号*/
                    presenter.modifyUserInfo("phone", content);
                    editTextDialog.dismiss();
                }

                @Override
                public void doCancel() {
                    editTextDialog.dismiss();
                }
            });
        } else if (id == R.id.rl_email) {
            //修改邮箱dialog
            final EditTextDialog editTextDialog2 = new EditTextDialog(this, getString(R.string.email), getString(R.string.hint_setting_email));
            editTextDialog2.show();
            editTextDialog2.setClicklistener(new EditTextDialog.ClickListenerInterface() {
                @Override
                public void doConfirm(String content) {
                    if (TextUtils.isEmpty(content)) {
                        ToastMessage(getResources().getString(R.string.wrongful_email));
                        return;
                    }
                    if (!content.matches("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$")) {
                        ToastMessage(getResources().getString(R.string.wrongful_email));
                        return;
                    }
                    /**修改邮箱*/
                    presenter.modifyUserInfo("email", content);
                    editTextDialog2.dismiss();
                }

                @Override
                public void doCancel() {
                    editTextDialog2.dismiss();
                }
            });
        } else if (id == R.id.rl_modify_password) {
            if (!needIgnoreClick(v)) {
                presenter.sysSettingsInfo();
            }
        } else if (id == R.id.rl_icon) {
            // showAvatarDialog();
            applyPermissionsScan();
        } else if (id == R.id.test_url) {
        } else if (id == R.id.tv_logout) {
            /**提示注销登录*/
            String uploadedOfflineData = sharedPrefs.getString(Constant.UPLOADED_OFFLINE_DATA, "0");
            String message;
            //如果为1说明有未上传的任务提交
            if (uploadedOfflineData.equals("1")) {
                message = getString(R.string.unsubmitted_task_message);
            } else {
                message = getString(R.string.is_logout);
            }
            showLogoutDialog(message, false);
        } else if (id == R.id.tv_zhuxiao) {
            /**提示注销登录*/
            String uploadedOfflineData = sharedPrefs.getString(Constant.UPLOADED_OFFLINE_DATA, "0");
            String message;
            //如果为1说明有未上传的任务提交
            if (uploadedOfflineData.equals("1")) {
                message = getString(R.string.unsubmitted_task_message);
            } else {
                message = getString(R.string.is_logout);
            }
            showLogoutDialog(message, true);
        }

    }

    EditPwdDialog editPwdDialog;

    /**
     * 修改密码
     *
     * @param type 0 老方式  1 新的弹窗
     */
    private void editPwd(int type) {
        if (type == 0) {
            //修改密码的dialog
            final ChangePasswordDialog changePasswordDialog = new ChangePasswordDialog(this);
            changePasswordDialog.show();
            changePasswordDialog.setClicklistener(new ChangePasswordDialog.ClickListenerInterface() {
                @Override
                public void doConfirm(String initialPassword, String newPassword, String againPassword) {
                    //修改密码接口
                    String appName = (String) Utility.getMetaData(context, Constant.APP_NAME);
                    if (Constant.APP_NAME_ZSJ.equals(appName)) {
                        //修改密码接口
                        presenter.getSM2Key(initialPassword, newPassword, againPassword);
                    } else {
                        //修改密码接口
                        presenter.modifyPassword(initialPassword, newPassword, againPassword);
                    }
                    changePasswordDialog.dismiss();
                }

                @Override
                public void doCancel() {
                    changePasswordDialog.dismiss();
                }
            });
        } else {
            if (editPwdDialog != null) {
                editPwdDialog.dismiss();
            }
            editPwdDialog = new EditPwdDialog(PresionInfoActivity.this, "", user.getRecord().getLoginId(),
                    new EditPwdDialog.ClickiInterface() {
                        @Override
                        public void clickSure(String username, String loginOldPwd, String loginNewPwd) {
                            presenter.editPwd(username, loginOldPwd, loginNewPwd, "0");
                        }

                        @Override
                        public void clickCancel(String pwdChangeDec) {
                            editPwdDialog.dismiss();
                        }
                    });

            editPwdDialog.show();
            editPwdDialog.setIsShowYuan("1");
        }
    }

    /**
     * 弹出上传图片提示框
     */
    private void showUploadDialog(List<Record> list) {
//        iamgeDialog = new UploadIamgeDialog(this, getString(R.string.uploading_the_picture));
//        iamgeDialog.show();
        loadingDialog.setText(getResources().getString(R.string.uploading));
        showLoading();
        //上传数据库图片
        for (int i = 0; i < list.size(); i++) {
            presenter.uploadDBImg(list.get(i), i);
        }
    }


    /**
     * 弹出注销提示框
     */
    private void showLogoutDialog(String message, final boolean isZhuxiao) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.dialog_prompt);
        builder.setMessage(message);
        builder.setCancelable(false);
        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, int which) {
                dialog.dismiss();
                //获取数据库是否保存有未上传的图片
                recordList = DBManager.getDBManager(PresionInfoActivity.this).getRecords(IMAGE.TABLE_NAME, null);
                if (recordList.size() > 0) {
                    /**提示上传图片*/
                    showUploadDialog(recordList);
                } else {
                    presenter.logout();
                    if (isZhuxiao) {
                        sharedPrefs.edit().putBoolean("zhuxiao", true).commit();
                    }
                    logoutSuccess();
                }
                CacheHelper.getInstance().clearCatch();
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * 头像提示框
     */
    private void showAvatarDialog() {
        final AvatarSelectDialog avatarSelectDialog = new AvatarSelectDialog(this);
        avatarSelectDialog.show();
        avatarSelectDialog.setClicklistener(new AvatarSelectDialog.ClickListenerInterface() {
            @Override
            public void takePhoto() {//拍照
//                if (Build.BRAND.equalsIgnoreCase("samsung")) {
////                    Intent intent = new Intent(PresionInfoActivity.this, CameraActivity.class);
////                    intent.putExtra("imagename", Constant.SRCAVATAR);
////                    intent.putExtra("position", Camera.CameraInfo.CAMERA_FACING_BACK);
////                    startActivityForResult(intent, 2);
//                    Intent intent = new Intent(PresionInfoActivity.this, CameraActivity.class);
//                    intent.putExtra("imagename", Constant.TEMPSRCAVATAR);
//                    startActivityForResult(intent, 2);
//                } else {
//                    //其他型号用原生的就可以，CameraActivity相机在有的型号无法自动对焦
//                    Utility.startPhotoActivity(PresionInfoActivity.this, 2, Constant.TEMPSRCAVATAR);
//                }

                //拍照并剪裁
                ImageSelector.builder()
                        .setCrop(true)
                        .setCropRatio(1.0f)// 设置是否使用图片剪切功能。
                        .onlyTakePhoto(true)  // 仅拍照，不打开相册
                        .start(PresionInfoActivity.this, 22);


                avatarSelectDialog.dismiss();
            }

            @Override
            public void selectAlubm() {//从相册选择
//                Intent intent = new Intent(Intent.ACTION_PICK, null);
//                intent.setDataAndType(
//                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
//                        "image/*");
//                startActivityForResult(intent, 1);
                //单选
                ImageSelector.builder()
                        .useCamera(false) // 设置是否使用拍照
                        .setSingle(true)  //设置是否单选
                        .setCrop(true)
                        .setCropRatio(1.0f)// 设置是否使用图片剪切功能。
                        .canPreview(true) //是否可以预览图片，默认为true
                        .start(PresionInfoActivity.this, 22); // 打开相册

                avatarSelectDialog.dismiss();
            }
        });
    }

    /**
     * 设置个人信息
     *
     * @param record
     */
    private void setUserInfo(User.Record record) {
//        //设置头像
//        File avatarFile = new File(ImageUtils.getImagePath(Constant.SRCAVATAR));
//        if (avatarFile.exists()) {
//            Bitmap bitmap = BitmapFactory.decodeFile(avatarFile.getPath());
//            if (bitmap != null) {
//                myAvatar.setImageBitmap(bitmap);
//            } else {
//                myAvatar.setImageResource(R.mipmap.icon_default_avatar);
//            }
//        }else {
        /**如果没有本地图片缓存网络图片并加载*/
        presenter.getIconUrl();
//        }
        //姓名
        tvFullname.setText(record.getUserName());
        //账号
        tvAccount.setText(record.getLoginId());
        //手机号
        if (!TextUtils.isEmpty(record.getPhone())) {
            tvPhone.setText(AESUtil.decryptAESExpand(record.getPhone()));
        }
        //邮箱
        if (!TextUtils.isEmpty(record.getEmail())) {
            tvEmail.setText(record.getEmail());
        }
        //职位
        tvPost.setText(record.getEmployeeType());
        //部门
        tvDepartment.setText(record.getDepartment());
    }


    /**
     * 修改手机号或者邮箱成功
     *
     * @param type
     */
    @Override
    public void modifyUserInfoSuccess(String type, String content) {
        User user = UserHelper.getSavedUser();
        User.Record record = user.getRecord();
        if (type.equals("phone")) {
            tvPhone.setText(content);
            record.setPhone(content);

        } else if (type.equals("email")) {
            tvEmail.setText(content);
            record.setEmail(content);
        }
        user.setRecord(record);
        UserHelper.saveUser(user);
    }

    /**
     * 上传头像图片成功
     *
     * @param
     */
    @Override
    public void uploadImgForClientSuccess() {
        File avatarFile = new File(ImageUtils.getImagePath(Constant.TEMPSRCAVATAR, this));
        if (avatarFile.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(avatarFile.getPath());
            if (bitmap != null) {
                myAvatar.setImageBitmap(bitmap);
            } else {
                myAvatar.setImageResource(R.mipmap.icon_default_avatar);
            }
        }
    }

    /**
     * 上传头像图片成功
     *
     * @param
     */
    @Override
    public void uploadImgForClientSuccess(File file) {
        if (file.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
            if (bitmap != null) {
                myAvatar.setImageBitmap(bitmap);
            } else {
                myAvatar.setImageResource(R.mipmap.icon_default_avatar);
            }
        }
    }


    /**
     * 上传头像图片失败
     */
    @Override
    public void uploadImgForClientOnError() {
//        File avatarFile = new File(ImageUtils.getImagePath(Constant.SRCAVATAR));
//        if (avatarFile.exists()) {
//            avatarFile.delete();
//        }
        ToastMessage(R.string.iamge_upload_failure);

        myAvatar.setImageResource(R.mipmap.icon_default_avatar);
    }


    /**
     * 上传数据库图片到服务器失败
     */
    @Override
    public void uploadDBImgOnError() {
//        if (iamgeDialog.isShowing())
//            iamgeDialog.dismiss();
        hideLoading();
        ToastMessage(R.string.iamge_upload_failure);
        logoutSuccess();
    }

    /**
     * 上传数据库图片到服务器成功
     */
    @Override
    public void uploadDBImgsuccess(Record record, int i) {
        //如果是最后一张图片
        if (recordList.size() == i + 1) {
//            if (iamgeDialog.isShowing())
//                iamgeDialog.dismiss();
            hideEmptyHint();
            logoutSuccess();
        }
        //删除H5离线拍摄上传成功之后相关的图片
        Utility.deleteH5Image(this, record);
    }

    @Override
    public void getIconUrlSuccess(String base64) {
        ImageUtils.base64ToBitmap(base64, ImageUtils.getImagePath(Constant.SRCAVATAR, this));//将base64转为bitmap存到本地文件
        final String path = ImageUtils.getImagePath(Constant.SRCAVATAR, this);
        File file = new File(path);
        if (file.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            if (bitmap == null) {
                myAvatar.setImageResource(R.mipmap.icon_default_avatar);
            } else {
                myAvatar.setImageBitmap(bitmap);
            }
            return;
        }
    }

    @Override
    public void getIconUrlError() {
        final String path = ImageUtils.getImagePath(Constant.TEMPSRCAVATAR, this);
        File file = new File(path);
        if (file.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            if (bitmap == null) {
                myAvatar.setImageResource(R.mipmap.icon_default_avatar);
            } else {
                myAvatar.setImageBitmap(bitmap);
            }
            return;
        }
    }

    @Override
    public void sysSettingsInfoSucess() {
        editPwd(1);
    }

    @Override
    public void sysSettingsInfoFaiture() {
        editPwd(0);
    }

    @Override
    public void updatePwdSuccess(String newPwd) {
        if (editPwdDialog != null) {
            editPwdDialog.dismiss();
        }
        ToastUtils.showShort(this, getResources().getString(R.string.change_success));
        PreferencesHelper.saveData("user_password", newPwd);
        //到登录页面
        logoutSuccess();
    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent data) {
        super.onActivityResult(arg0, arg1, data);
        if (arg0 == 22 && data != null) {
            //获取选择器返回的数据
            ArrayList<String> images = data.getStringArrayListExtra(
                    ImageSelector.SELECT_RESULT);
            if (images == null || images.size() == 0) {
                return;
            }
            String imageFile = images.get(0);
            File file = new File(imageFile);
            new ImageCompressor(context).compressImageInPlace(file.getPath(), new OnCompressListener() {
                @Override
                public void onStart() {
                }

                @Override
                public void onSuccess(File f) {
                    presenter.uploadImgForClient(f);
                }

                @Override
                public void onError(Throwable e) {
                    presenter.uploadImgForClient(file);
                }
            });


        }

//        getTakePhoto().onActivityResult(arg0,arg1,data);
//        if (arg1 == RESULT_OK)
//            switch (arg0) {
//                case 1:
//                    CropOptions.Builder builder=new CropOptions.Builder();
//                    builder.setWithOwnCrop(false);
//                    builder.setAspectX(1).setAspectY(1);
//                    CompressConfig compressConfig=new CompressConfig.Builder().setMaxSize(10*1024).setMaxPixel(800).create();
//                    getTakePhoto().onEnableCompress(compressConfig,false);
//                    try {
//                        getTakePhoto().onCrop(data.getData(),Uri.fromFile(new File(ImageUtils.getImagePath(Constant.TEMPSRCAVATAR,this))),builder.create());
//                    } catch (TException e) {
//                        e.printStackTrace();
//                    }
//                    break;
//            }
//        if (arg1 == RESULT_OK)
//            switch (arg0) {
//                case 1:
//
////                    myAvatar.setImageBitmap(bitmap);
//                    tackType = 1;
//                    cropPhoto(data.getData());
//                    break;
//                // 如果是调用相机拍照时
//                case 2:
//                    tackType = 0;
////                    ImageUtils.readPictureDegree(ImageUtils.getImagePath(Constant.SRCAVATAR));
//                    File temp = new File(ImageUtils.getImagePath(Constant.TEMPSRCAVATAR, this));
//                    if (Build.VERSION.SDK_INT == 34) {
//                        try {
//                            presenter.uploadImgForClient(new Compressor(this)
//                                    .setMaxWidth(160)
//                                    .setMaxHeight(160)
//                                    .setQuality(100)
//                                    .compressToFile(temp));
//                        } catch (IOException e) {
//                            ToastUtils.showShort(context, "E:" + e.getMessage());
//                            // presenter.uploadImgForClient(file111);
//                        }
//                    } else {
//                        if (Build.VERSION.SDK_INT >= 23) {
//                            cropPhoto(FileProvider.getUriForFile(this, getApplication().getPackageName() + ".fileprovider", temp));
////                        intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(activity, activity.getApplication().getPackageName()+".fileprovider", new File(ImageUtils.getImagePath(fileName,activity))));
//                        } else {
//                            cropPhoto(data.getData());
//                        }
//                    }
//                    //  cropPhoto(data.getData());
////                    startPhotoZoom(Uri.fromFile(temp));
//                    break;
//                // 取得裁剪后的图片
//                case 3:
//                    if (data != null) {
//                        setPicToView(data);
//                    }
//                    break;
//
//
//            }
    }

    public static Uri getFileUri(Context context, File file) {
        if (file == null || !file.exists()) {
            throw new IllegalArgumentException("File is null or does not exist.");
        }

        // 使用 FileProvider 生成内容 URI
        Uri contentUri = FileProvider.getUriForFile(context,
                context.getPackageName() + ".fileprovider",
                file);

        return contentUri;
    }

    private int tackType;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    //注销后跳转到登录
    public void logoutSuccess() {
        hideLoading();
        //点击注销后将此值重置为0
        sharedPrefs.edit().putString(Constant.UPLOADED_OFFLINE_DATA, "0").apply();
        if (H5Activity.instance != null) {
            H5Activity.instance.finish();
        }

        Utility.startLoginActivityOrClearData(context);
        H5UploadImage h5UploadImage = new H5UploadImage();
        h5UploadImage.setUploadImageType(Constant.LOGOUT_CLOSE_GPS);
        RxBus.getDefault().send(h5UploadImage);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    String pathNew;

    private void cropPhoto(Uri uri) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//            //虽然getExternalStoragePublicDirectory方法被淘汰了，但是不影响使用
//           // pathNew = (Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) + "crop_image.jpg");
////            pathNew= Environment.getExternalStorageDirectory()+"crop_image.jpg";
////            if (Build.VERSION.SDK_INT > 29) {
//                pathNew = getExternalFilesDir(null).getAbsolutePath() +"crop_image.jpg";
////            }
////            pathNew = (getExternalFilesDir(DIRECTORY_PICTURES) + "crop_image.jpg");
//        } else {
//            pathNew = (getExternalCacheDir() + "crop_image.jpg");
//        }


        try {
            File directory = getExternalFilesDir(null);
            if (directory == null) {
                directory = context.getFilesDir();
            }
            if (directory == null) {
                pathNew = uriToFileToFile(context, uri).getPath();
            } else {
                pathNew = directory.getAbsolutePath() + "crop_image.jpg";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        Uri contentUri = Uri.fromFile(new File(pathNew));
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //Android 7.0需要临时添加读取Url的权限， 添加此属性是为了解决：调用裁剪框时候提示：图片无法加载或者加载图片失败或者无法加载此图片
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");//发送裁剪信号，去掉也能进行裁剪
        // intent.putExtra("scale", true);// 设置缩放
        // intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //上述两个属性控制裁剪框的缩放比例。
        //当用户用手拉伸裁剪框时候，裁剪框会按照上述比例缩放。
        intent.putExtra("outputX", 150);//属性控制裁剪完毕，保存的图片的大小格式。
        intent.putExtra("outputY", 150);//你按照1:1的比例来裁剪的，如果最后成像是800*400，那么按照2:1的样式保存，intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());//输出裁剪文件的格式
        intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);//设置输出路径
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }


    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */

    private boolean isHeardPhoto;
    private File file111;

    private void setPicToView(Intent picdata) {
//        XLog.i("picdata"+picdata);
//        Bundle extras = picdata.getExtras();
//        if (extras != null) {
        if (picdata == null || picdata.getData() == null) {
            file111 = new File(pathNew);
        } else {
            file111 = uriToFileApiQ(picdata.getData(), this);
        }
        /**上传图片*/
        isHeardPhoto = true;
//        presenter.uploadImgForClient(file111);
        try {
            presenter.uploadImgForClient(new Compressor(this)
                    .setMaxWidth(160)
                    .setMaxHeight(160)
                    .setQuality(100)
                    .compressToFile(file111));
        } catch (IOException e) {
            ToastUtils.showShort(context, "E:" + e.getMessage());
            // presenter.uploadImgForClient(file111);
        }
//        }
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView2(Intent picdata) {
//        XLog.i("picdata"+picdata);
//        Bundle extras = picdata.getExtras();
//        if (extras != null) {
        FileOutputStream fos = null;
        try {
            Bitmap photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
            XLog.i("uritempFile" + uritempFile);
            XLog.i("picdata" + photo);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] b = stream.toByteArray(); // 将图片流以字符串形式存储下来
            File file = new File(ImageUtils.getImagePath(Constant.TEMPSRCAVATAR, this));
            if (file.exists()) {
                file.delete();
            }
            fos = new FileOutputStream(file);
            fos.write(b);
        } catch (FileNotFoundException e) {
            ToastMessage("没有输出文件");
        } catch (IOException e) {
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
        /**上传图片*/
        presenter.uploadImgForClient();

//        }
    }

    private void updateToIcon(String url) {

        FileOutputStream fos = null;
        try {
            Bitmap photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(
//                    Uri.parse("file://" + url)
                    FileProvider.getUriForFile(this, getApplication().getPackageName() + ".fileprovider",
                            new File(url))
            ));

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] b = stream.toByteArray(); // 将图片流以字符串形式存储下来
            File file = new File(ImageUtils.getImagePath(Constant.TEMPSRCAVATAR, this));
            if (file.exists()) {
                file.delete();
            }
            fos = new FileOutputStream(file);
            fos.write(b);
        } catch (FileNotFoundException e) {
            ToastMessage("没有输出文件");
        } catch (IOException e) {
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
        /**上传图片*/
        presenter.uploadImgForClient();

    }

    List<String> permissionLists1 = new ArrayList<>();
    List<String> permissionLists2 = new ArrayList<>();

    private void applyPermissionsScan() {
        if (Build.VERSION.SDK_INT >= 23) {
            permissionLists1.clear();
            permissionLists2.clear();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionLists2.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionLists2.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissionLists1.add(Manifest.permission.CAMERA);
            }

            if (!permissionLists1.isEmpty()) {//说明肯定有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists1.toArray(new String[permissionLists1.size()]), 1);
                snackbar = SnackBarUtil.show(this, "获取拍摄照片和录制内容的权限说明：", "用于拍照");
            } else if (!permissionLists2.isEmpty()) {
                ActivityCompat.requestPermissions(this, permissionLists2.toArray(new String[permissionLists2.size()]), 2);
                snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片");
            } else {
                showAvatarDialog();
            }

        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[],
                                           int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_scan_per_cunchu));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                    //其他逻辑(这里当权限都同意的话就执行打电话逻辑)
//                    nativeTakePhoto();
                }

                if (!permissionLists2.isEmpty()) {
                    ActivityCompat.requestPermissions(this, permissionLists2.toArray(new String[permissionLists2.size()]), 2);
                    snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片");
                }
                break;
            case 2:
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_scan_per_cunchu));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                    //其他逻辑(这里当权限都同意的话就执行打电话逻辑)
//                    nativeTakePhoto();
                }
                break;
            default:
                break;
        }
    }


    public static File uriToFileApiQ(Uri uri, Context context) {
        File file = null;
        if (uri == null) return file;
        //android10以上转换
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
            ContentResolver contentResolver = context.getContentResolver();
            String displayName = System.currentTimeMillis() + Math.round((Math.random() + 1) * 1000)
                    + "." + MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri));

            try {
                InputStream is = contentResolver.openInputStream(uri);
                File cache = new File(context.getCacheDir().getAbsolutePath(), displayName);
                FileOutputStream fos = new FileOutputStream(cache);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    FileUtils.copy(is, fos);
                }
                file = cache;
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    //获取文件的Content uri路径
    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }


    //    ----
    public File uriToFile(Context context, Uri uri) throws IOException {
        if (uri == null) {
            return null;
        }

        String scheme = uri.getScheme();
        if (scheme == null || scheme.equals("file")) {
            return new File(uri.getPath());
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return new File(Environment.getExternalStorageDirectory(), split[1]);
                }

                // Handle non-primary volumes
                StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
                try {
                    Class<?> storageVolumeClass = Class.forName("android.os.storage.StorageVolume");
                    Method getVolumeList = storageManager.getClass().getMethod("getVolumeList");
                    Method getUuid = storageVolumeClass.getMethod("getUuid");
                    Method getState = storageVolumeClass.getMethod("getState");
                    Method getPath = storageVolumeClass.getMethod("getPath");

                    Object result = getVolumeList.invoke(storageManager);
                    final int length = Array.getLength(result);
                    for (int i = 0; i < length; i++) {
                        Object storageVolumeElement = Array.get(result, i);
                        String uuid = (String) getUuid.invoke(storageVolumeElement);
                        if (uuid != null && uuid.equalsIgnoreCase(type)) {
                            String state = (String) getState.invoke(storageVolumeElement);
                            if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                                return new File((String) getPath.invoke(storageVolumeElement), split[1]);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(id));
                return getFileFromContentUri(context, contentUri);
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getFileFromContentUri(context, contentUri, selection, selectionArgs);
            }
        } else if ("content".equalsIgnoreCase(scheme)) {
            return getFileFromContentUri(context, uri);
        } else if ("file".equalsIgnoreCase(scheme)) {
            return new File(uri.getPath());
        }

        return null;
    }

    private boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private File getFileFromContentUri(Context context, Uri contentUri) throws IOException {
        return getFileFromContentUri(context, contentUri, null, null);
    }

    private File getFileFromContentUri(Context context, Uri contentUri, String selection, String[] selectionArgs) throws IOException {
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(contentUri, null, selection, selectionArgs, null);
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
                    if (columnIndex != -1) {
                        String filePath = cursor.getString(columnIndex);
                        return new File(filePath);
                    }
                }
            } finally {
                cursor.close();
            }
        }

        // 如果无法获取文件路径，创建临时文件
        return createTempFile(context, contentUri);
    }

    private File createTempFile(Context context, Uri uri) throws IOException {
        InputStream inputStream = context.getContentResolver().openInputStream(uri);
        File file = File.createTempFile("temp", ".tmp", context.getCacheDir());
        FileOutputStream outputStream = new FileOutputStream(file);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }

        inputStream.close();
        outputStream.close();

        return file;
    }


    public File uriToFileToFile(Context context, Uri uri) throws IOException {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // 获取输入流
            inputStream = context.getContentResolver().openInputStream(uri);
            if (inputStream == null) {
                throw new IOException("Failed to open input stream for URI: " + uri);
            }

            // 创建临时文件
            File tempFile = createTempFile(context);

            // 获取输出流
            outputStream = new FileOutputStream(tempFile);

            // 将输入流的数据写入输出流
            byte[] buffer = new byte[4 * 1024]; // 4KB 缓冲区
            int read;
            while ((read = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }
            outputStream.flush();

            return tempFile;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

    private File createTempFile(Context context) throws IOException {
        String fileName = "temp_image.jpg";
        File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(fileName, ".jpg", storageDir);
    }


}
